<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="单据号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input v-model="model.billNo" placeholder="请输入单据号" disabled=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billDate">
              <j-date placeholder="请选择单据日期" v-model="model.billDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="业务类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billType">
              <j-dict-select-tag type="list" v-model="model.billType" dictCode="mm_material_picking_ret_bill_type" placeholder="请选择业务类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="库房" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseId">
              <j-search-select-tag ref="warehouseSearch" v-model="model.warehouseId" dict="mdm_warehouse,warehouse_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="领用人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiver">
              <j-select-user-by-dep v-model="model.receiver" :multi="false" @change="receiverChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="制单人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maker">
              <j-select-user-by-dep v-model="model.maker" :multi="false"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <j-search-select-tag v-model="model.projectId" dict="quote_project,project_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-textarea v-model="model.remark" rows="1" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="退回明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mmMaterialPickingRetDetailTable.loading"
          :columns="mmMaterialPickingRetDetailTable.columns"
          :dataSource="mmMaterialPickingRetDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @added="materialDetailAdded"
          @valueChange = "detailMaterialChange">

          <div slot="buttonBefore" >
            <div class="action-button">
              <a-button slot="buttonBefore" type="primary" icon="plus" @click="chooseMaterial" :disabled="formDisabled">新增</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="materialPopReport" code="mdm_popup_bom_material" multi="true" @ok="materialPopupCallback"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import {curDate, genBillNo, loginUsername, loginOrgCode, getOrgCodeByUsername} from '@/utils/util'
  import {initDictOptions} from "@/components/dict/JDictSelectUtil";

  export default {
    name: 'MmMaterialPickingRetForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          status: '01',
          billDate: curDate(),
          billType: '01',
          maker: loginUsername(),
          receiver: loginUsername(),
          receiverDept: loginOrgCode()
        },
        warehouseUpdateCancel: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           billNo: [
              { required: true, message: '请输入单据号!'},
           ],
           billDate: [
              { required: true, message: '请输入单据日期!'},
           ],
           billType: [
              { required: true, message: '请输入业务类型!'},
           ],
          warehouseId: [
            { required: true, message: '请输入库房!'},
          ],
        },
        refKeys: ['mmMaterialPickingRetDetail', ],
        tableKeys:['mmMaterialPickingRetDetail', ],
        activeKey: 'mmMaterialPickingRetDetail',
        // 材料领用明细
        mmMaterialPickingRetDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode:"mdm_popup_bom_material",
              orgFields: 'material_id,material_code,material_desc,material_unit_code,material_batch_flag',
              destFields: 'materialId,materialNo,materialDesc,unit,materialBatchFlag',
              width:"260px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.sel_search,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '数量',
              key: 'qty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              scale: 2,
              validateRules: [
                { required: true, message: '${title}不能为空' },
                { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入大于零的数' },
              ],
            },
            {
              title: '单价',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '金额',
              key: 'sumPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '批次',
              key: 'batchNo',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [
                {
                  handler(type, value, row, column, callback, target){
                    if( type === 'blur' || type === 'getValues'){
                      let {values} = target.getValuesSync({ validate: false, rowIds: [row.id] });
                      let materialBatchFlag = values[0].materialBatchFlag;
                      if(materialBatchFlag === '1' && (value == null || value === '')){
                        callback(false, '${title}不能为空')
                        return
                      }else{
                        callback(true)
                      }
                    }else{
                      callback();
                    }
                  },
                }
              ],
            },
            {
              title: '库位',
              key: 'storageLocationId',
              type: FormTypes.sel_search,
              dictCode:"mdm_storage_location,location_no,id",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [
                {
                  handler(type, value, row, column, callback, target){
                    if( type === 'blur' || type === 'getValues'){
                      let {values} = target.getValuesSync({ validate: false, rowIds: [row.id] });
                      let storageLocationFlag = values[0].storageLocationFlag;
                      if(storageLocationFlag === '1' && (value == null || value === '')){
                        callback(false, '${title}不能为空')
                        return
                      }else{
                        callback(true)
                      }
                    }else{
                      callback();
                    }
                  },
                }
              ],
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行号',
              key: 'lineNo',
              type: FormTypes.inputNumber,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '库位管理',
              key: 'storageLocationFlag',
              type: 'hidden',
              defaultValue: '0'
            },
            {
              title: '退出数量',
              key: 'outQty',
              type: FormTypes.hidden,
              defaultValue: 0,
            },
            {
              title: '物料',
              key: 'materialId',
              type: FormTypes.hidden,
            },
            {
              title: '物料编号',
              key: 'materialNo',
              type: FormTypes.hidden,
            },
            {
              title: '批次管理',
              key: 'materialBatchFlag',
              type: 'hidden',
            },
          ]
        },
        url: {
          add: "/mm/materialPickingRet/add",
          edit: "/mm/materialPickingRet/edit",
          queryById: "/mm/materialPickingRet/queryById",
          mmMaterialPickingRetDetail: {
            list: '/mm/materialPickingRet/queryMmMaterialPickingRetDetailByMainId'
          },
          warehouse:{
            queryById: '/mdm/warehouse/queryById'
          }
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    watch:{
      'model.warehouseId': {
        deep: true,
        handler(newVal, oldVal) {
          if(this.warehouseUpdateCancel){
            this.warehouseUpdateCancel = false;
            return;
          }
          let storageLocationId = this.mmMaterialPickingRetDetailTable.columns[6];
          let storageLocationFlag = this.mmMaterialPickingRetDetailTable.columns[9];
          if(!newVal) {
            storageLocationId.options = [];
            storageLocationFlag.defaultValue = '0';
            return;
          }
          let mmMaterialPickingRetDetailTable = this.$refs[this.refKeys[0]];
          let {values} = mmMaterialPickingRetDetailTable.getValuesAsync({validate: false})
          if(values && values.length > 0){
            let hasVal = values.some(row => row.storageLocationId)
            if(hasVal){
              this.$message.error("明细已经填写库位，不能修改库房!")
              this.warehouseUpdateCancel = true;
              let warehouseSearch = this.$refs['warehouseSearch'];
              warehouseSearch.handleChange(oldVal);
              return;
            }
          }
          // 获取库房信息
          getAction(this.url.warehouse.queryById,{id: newVal}).then(warehouseRes =>{
            if(warehouseRes.success){
              // 库位管理设置
              let locationFlag = warehouseRes.result.locationFlag || '0';
              storageLocationFlag.defaultValue = locationFlag;
              if(values && values.length > 0){
                for(let i=0; i<values.length; i++){
                  mmMaterialPickingRetDetailTable.setValues([{rowKey: values[i].id, values: {storageLocationFlag: locationFlag}}]);
                }
              }
              // 设置库位下拉选项
              let dictCode = "mdm_storage_location,location_no,id" + encodeURIComponent(",enable_flag='1' and warehouse_id='"+ newVal +"'")
              initDictOptions(dictCode).then(res => {
                if (res.success && res.result.length>0) {
                  storageLocationId.options = res.result;
                  if(values && values.length > 0){
                    for(let i=0; i<values.length; i++){
                      mmMaterialPickingRetDetailTable.setValues([{rowKey: values[i].id, values: {storageLocationId: null}}]);
                    }
                  }
                } else {
                  storageLocationId.options = []
                  this.$message.error("未找到库位信息!")
                }
              })
            }else{
              this.$message.error("未找到库房信息!")
            }
          })
        }
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        genBillNo('46', this, 'billNo');
        this.mmMaterialPickingRetDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.mmMaterialPickingRetDetail.list, params, this.mmMaterialPickingRetDetailTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          mmMaterialPickingRetDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      chooseMaterial(){
        if(!this.model.warehouseId){
          this.$message.error("请先选择库房！")
          return;
        }
        this.$refs.materialPopReport.show();
      },
      detailMaterialChange(parm){
        if(!parm || !parm['column'] || !parm['row'] || !parm['target']){
          return;
        }
        let cols = ['qty','sumPrice','unitPrice'];
        let key = parm.column.key;
        if(cols.includes(key)){
          let editableTable = parm['target'];
          if(key === cols[0] || key === cols[2]){
            // 数量、单价更新，重新计算当前行金额
            let unitPrice = parm.row[cols[2]] || 0;
            let qty = parm.row[cols[0]] || 0;
            let sumPrice = this.$math.round(this.$math.multiply(unitPrice , qty));
            editableTable.setValues([{rowKey: parm.row.id, values: {[cols[1]]: sumPrice}}]);
          }
          if(key === cols[1]){
            // 金额更新，重新计算单价
            let sumPrice = parm.row[cols[1]] || 0;
            let qty = parm.row[cols[0]] || 0;
            if(qty != 0){
              let unitPrice = this.$math.round(this.$math.divide(sumPrice , qty));
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[2]]: unitPrice}}]);
            }
          }
        }
      },
      materialPopupCallback(rows){
        if(rows && rows.length > 0){
          let materialPickingRetDetail = this.$refs[this.refKeys[0]];
          let oldData = materialPickingRetDetail.getValuesSync();
          let column = this.mmMaterialPickingRetDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = column.orgFields.split(',');
          let destFieldsArr = column.destFields.split(',');
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              materialPickingRetDetail.add();
            }
            addRow = materialPickingRetDetail.rows[materialPickingRetDetail.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            materialPickingRetDetail.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
      materialDetailAdded: function (obj) {
        let editTable = this.$refs[this.refKeys[0]];
        let lineNo = this.generateLineNo();
        editTable.setValues([{rowKey: obj.row.id, values:{lineNo: lineNo}}])
      },
      /** 生成行号 */
      generateLineNo(){
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows;
        let num = 10;
        if(rows.length > 1){
          let lastId = editTable.getCleanId(rows[rows.length-2].id)
          let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
          num = Number(values[0].lineNo) + 10
        }
        return num
      },
      async receiverChanged(newVal) {
        this.model.receiverDept = await getOrgCodeByUsername(newVal);
      }
    }
  }
</script>

<style scoped>
.action-button {
  margin-bottom: 8px;
}
.gap {
  padding-left: 8px;
}
</style>